import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_plugin_test/flutter_plugin_test.dart';
import 'package:flutter_plugin_test/flutter_plugin_test_method_channel.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = "";
  int selectedIndex = 0;
  List<Map<String, dynamic>>? musics=[];
  bool status = false;
  final _flutterPluginTestPlugin = FlutterPluginTest();

  @override
  void initState() {
    super.initState();
    // initPlatformState();
    initMusics();
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _flutterPluginTestPlugin.getPlatformVersion() ?? '未知的平台版本';
    } on PlatformException {
      platformVersion = '未能获得平台版本。';
    }
    if (!mounted) return;
    setState(() {
      _platformVersion = platformVersion;
    });
  }
  ///获取时间
  Future<void> getCurrentPosition()async{
    PositionInfo positionInfo = await _flutterPluginTestPlugin.getCurrentPosition();
    print("positionInfo: position-${positionInfo.position} duration-${positionInfo.duration}");
  }

  ///获取音乐
  Future<void> initMusics() async {
    print("initMusics0");
    var list2 = await _flutterPluginTestPlugin.initMusics();
    setState(() {
      musics = list2;
    });
  }
  ///播放
  Future<void> playMusic(int index) async {
    setState(() {
      status = true;
    });
    var result = await _flutterPluginTestPlugin.playMusic(index);
    print("播放 result: $result");
  }
  ///开始或继续
  Future<void> startMusic() async {
    setState(() {
      status = !status;
    });
    var result = await _flutterPluginTestPlugin.startMusic();
    print("开始或继续 result: $result");
  }
  ///停止(结束)
  Future<void> stopMusic() async {
    setState(() {
      status = false;
    });
    var result = await _flutterPluginTestPlugin.stopMusic();
    print("停止(结束) result: $result");
  }
  ///上一首
  Future<void> lastClick() async {
    setState(() {
      status = true;
      selectedIndex--;
      if(selectedIndex<0){
        selectedIndex=musics!.length;
      }
    });
    var result = await _flutterPluginTestPlugin.lastClick();
    print("上一首 result: $result");
  }
  ///下一首
  Future<void> nextClick() async {
    setState(() {
      status = true;
      selectedIndex++;
      if(selectedIndex>musics!.length){
        selectedIndex=0;
      }
    });
    var result = await _flutterPluginTestPlugin.nextClick();
    print("下一首 result: $result");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Music player"),
          backgroundColor: Colors.blueGrey,
          actions: [
            GestureDetector(
                onTap: (){
                  getCurrentPosition();
                },
                child: const Icon(Icons.access_time_outlined)),
            GestureDetector(
                onTap: (){
                  initMusics();
                },
                child: const Icon(Icons.refresh)),
          ],
        ),
        body: Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    Colors.white,
                    Colors.white,
                  ]
              )
          ),
          child: Column(
            children: [
              // Text("musics: ${musics}")
              Expanded(
                child: musics!.isEmpty?const SizedBox():Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 8),
                  child: ListView.separated(
                      itemCount: musics!.length,
                      separatorBuilder: (BuildContext context, int index) {
                        return const Divider();
                      },
                      itemBuilder: (BuildContext context, int index) {
                        return Container(
                          decoration: BoxDecoration(
                            color: selectedIndex==index?Colors.blueGrey:Colors.black12,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: ListTile(
                              onTap: (){
                                setState(() {
                                  selectedIndex = index;
                                  playMusic(index);
                                });
                              },
                              shape: const CircleBorder(),
                              selected:selectedIndex == index,
                              selectedColor:Colors.blue,
                              style: ListTileStyle.list,
                              title: Text(musics?[index]["musicFileName"],style: TextStyle(color: selectedIndex==index?Colors.white:Colors.black),),
                              subtitle: Text(musics?[index]["musicAuthor"],style: TextStyle(color: selectedIndex==index?Colors.white:Colors.black),),
                              // trailing: selectedIndex == index?Icon(Icons.check_box,color: Colors.blue,):Icon(Icons.check_box_outline_blank,color: Colors.grey,),
                            ),
                          ),
                        );
                      }),
                ),
              ),
              Container(
                color: Colors.blueGrey,
                child: Container(
                  // width: MediaQuery.of(context).size.width,
                  padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                  margin: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
                  height: 75,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      gradient: const LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            Colors.white,
                            Colors.white,
                          ]
                      )
                  ),
                  child: Material(
                    color: Colors.transparent,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                musics!.isEmpty?"":musics?[selectedIndex]["musicFileName"],
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                              ),
                              Text(musics!.isEmpty?"":musics?[selectedIndex]["musicAuthor"],
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                                style: const TextStyle(fontSize: 10),),
                            ],
                          ),
                        ),
                        InkWell(
                            onTap: (){
                              lastClick();
                            },
                            child: const Icon(Icons.skip_previous,size: 35,)),
                        InkWell(
                            onTap: (){
                              startMusic();
                            },child: Icon(!status?Icons.play_arrow:Icons.stop,size: 35,)),
                        InkWell(
                            onTap: (){
                              nextClick();
                            },child: const Icon(Icons.skip_next,size: 35,)),
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
